import type { NextApiRequest, NextApiResponse } from "next";
import { getServerAuthSession } from "@/src/server/auth";
import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== "POST") {
        return res.status(405).json({ error: "Method not allowed" });
    }

    const session = await getServerAuthSession({ req, res });
    if (!session || !session.user || !session.user.id) {
        return res.status(401).json({ error: "Unauthorized" });
    }

    try {
        await createProjectMembershipsOnSignup({
            id: session.user.id,
            email: session.user.email ?? null,
        });
        return res.status(200).json({ ok: true });
    } catch (error) {
        // Avoid leaking internal details
        return res.status(500).json({ error: "Failed to ensure membership" });
    }
}


